<?php
namespace app\admin\controller;
use app\admin\model\Users as UsersModel;
class Users extends Common{
    //会员列表
    public function index(){
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $list=db('users')->alias('u')
                ->join(config('database.prefix').'user_level ul','u.level = ul.level_id','left')
                ->field('u.*,ul.level_name')
                ->where('u.email|u.mobile|u.username','like',"%".$key."%")
                ->order('u.id desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['reg_time'] = date('Y-m-d H:s',$v['reg_time']);
                if($v['level']<3){
                    $list['data'][$k]['daili'] =$v['recount'] ;
                }elseif($v['level']>=3){
                    $sumachi=Db('users')->where('up_userid',$v['id'])->sum('dan');
                    $maxachi=Db('users')->where('up_userid',$v['id'])->max('dan');
                    $list['data'][$k]['daili']=$sumachi-$maxachi;
                }
                $list['data'][$k]['dansum']=Db('baodan')->where('userid',$v['id'])->sum('num');
				
				 if(!empty($v['up_userid'])){
					 $upuser=db('users')->where('id='.$v['up_userid'])->value('mobile');
					$list['data'][$k]['up_userid']=$upuser;
				}else{
					$list['data'][$k]['up_userid']='空';
					
				}
				if(!empty($v['center_id'])){
						 $upuser2=db('users')->where('id='.$v['center_id'])->value('mobile');
				 $list['data'][$k]['center_id']=$upuser2;
					
				}else{
					
					$list['data'][$k]['center_id']='空';
				}
				
				
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
	
	public function tixian(){
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
			
            $list=db('tixian')
			    ->alias('u')
                ->join('__USERS__ ul','ul.id = u.userid','left')
                ->field('u.id as bid,u.num,u.tixian_time,u.is_lock,u.type,u.is_ok,u.userid,u.shifa_qian,ul.*')
                ->where('ul.email|ul.mobile|ul.username','like',"%".$key."%")
                ->order('u.tixian_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
				
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['tixian_time'] = date('Y-m-d H:s',$v['tixian_time']);
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }//会员积分日志// 资金记录日志
	public function money_log(){
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
			
            $list=db('moneylogtype')
			    ->alias('u')
                ->join('__USERS__ ul','ul.id = u.userid','left')
                ->field('u.id as bid,u.num,u.time,u.type,u.source,u.beizhu,u.userid,u.dangqian,ul.*')
                ->where('ul.email|ul.mobile|ul.username','like',"%".$key."%")
                ->order('u.id desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
				
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['time'] = date('Y-m-d H:s',$v['time']);
                $list['data'][$k]['type_name']=money_log_type($v['source']);
                $list['data'][$k]['type']=tixiantype($v['type']);
			//变动类型处理 预留
				
				
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
	public function baodanlist(){
	
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
			
            $list=db('baodan')
			    ->alias('u')
                ->join('__USERS__ ul','ul.id = u.userid','left')
                ->field('u.id as bid,u.num,u.baodan_time,u.is_lock,u.type,u.is_ok,u.userid,ul.*')
                ->where('ul.email|ul.mobile|ul.username','like',"%".$key."%")
                ->order('u.baodan_time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
				
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['baodan_time'] = date('Y-m-d H:s',$v['baodan_time']);
				//判断报单中心是否存在
				if(!empty($v['center_id'])){
					
					$upuser=db('users')->where('id='.$v['center_id'])->value('mobile');
					$list['data'][$k]['center_id']=$upuser;
				}
				
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
	public function dingdanlist(){
	
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
			
            $list=db('shop_dingdan')
			    ->alias('u')
                ->join('__USERS__ ul','ul.id = u.userid','left')
                ->field('u.id as bid,u.num,u.pay_ok,u.time,u.shop_id,u.xiaofei,u.userid,u.is_ok,u.danhao,u.wuliuname,u.wuliuid,ul.*')
                ->where('ul.email|ul.mobile|ul.username','like',"%".$key."%")->where('pay_ok=1')
                ->order('u.time desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
				
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['time'] = date('Y-m-d H:s',$v['time']);
				$proname=db('shop')->where('id='.$v['shop_id'])->value('title');
				$list['data'][$k]['proname'] = $proname;
				
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
    //设置会员状态
    public function usersState(){
        $id=input('post.id');
        $is_lock=input('post.is_lock');
        $user=getuser($id);
        if($user['activation']==1){
            return ['status'=>0,'msg'=>'该会员已激活!'];
        }else{
            if(db('users')->where('id='.$id)->update(['activation'=>$is_lock])!==false){
            //    jihuo($id,1);
                return ['status'=>1,'msg'=>'设置成功!'];
            }else{
                return ['status'=>0,'msg'=>'设置失败!'];
            }
        }
    }
	 public function tixians(){
        $id=input('post.id');
        $is_lock=input('post.is_lock');
	
        if(db('tixian')->where('id='.$id)->update(['is_ok'=>$is_lock])!==false){
            return ['status'=>1,'msg'=>'设置成功!'];
        }else{
            return ['status'=>0,'msg'=>'设置失败!'];
        }
    }

    public function edit($id=''){
        if(request()->isPost()){
            $user = db('users');
            $data = input('post.');
            $level =explode(':',$data['level']);
            $data['level'] = $level[1];
            $province =explode(':',$data['province']);
            $data['province'] = isset( $province[1])?$province[1]:'';
            $city =explode(':',$data['city']);
            $data['city'] = isset( $city[1])?$city[1]:'';
            $district =explode(':',$data['district']);
            $data['district'] = isset( $district[1])?$district[1]:'';
			//判断积分是否被修改
			$userinfo=db('users')->where('id='.$id)->find();
			//此处写的很乱，有时间的时候重新封装算法  2018年8月1日19:05:51
			if($data['money_jifen']!=$userinfo['money_jifen']){
					//增加积分变动日志
					$addinfo['type']=1; //1为积分 2为 金钱 3 为本金  4 为其他
					$addinfo['userid']=$userinfo['id'];
					$addinfo['dangqian']=$data['money_jifen'];
					$addinfo['source']=4;//4 为管理员操作
					$addinfo['time']=time();
					$addinfo['beizhu']='管理员直接操作，无金额变动数量';
					db('money_log')->insert($addinfo);
					
				
			}
	/*		if($data['money_qian']!=$userinfo['money_qian']){
					//增加积分变动日志
					$addinfo['type']=2; //1为积分 2为 金钱 3 为本金  4 为其他
					$addinfo['userid']=$userinfo['id'];
					$addinfo['dangqian']=$data['money_qian'];
					$addinfo['source']=4;//4 为管理员操作
					$addinfo['time']=time();
					$addinfo['beizhu']='管理员直接操作，无金额变动数量';
					db('money_log')->insert($addinfo);


			}
			if($data['money_benjin']!=$userinfo['money_benjin']){
					//增加积分变动日志
					$addinfo['type']=3; //1为积分 2为 金钱 3 为本金  4 为其他
					$addinfo['userid']=$userinfo['id'];
					$addinfo['dangqian']=$data['money_benjin'];
					$addinfo['source']=4;//4 为管理员操作
					$addinfo['time']=time();
					$addinfo['beizhu']='管理员直接操作，无金额变动数量';
					db('money_log')->insert($addinfo);


			}
			if($data['money_qita']!=$userinfo['money_qita']){
					//增加积分变动日志
					$addinfo['type']=4; //1为积分 2为 金钱 3 为本金  4 为其他
					$addinfo['userid']=$userinfo['id'];
					$addinfo['dangqian']=$data['money_qita'];
					$addinfo['source']=4;//4 为管理员操作
					$addinfo['time']=time();
					$addinfo['beizhu']='管理员直接操作，无金额变动数量';
					db('money_log')->insert($addinfo);


			}
			*/
			if($data['money_baodan']!=$userinfo['money_baodan']){
					//增加积分变动日志
					$addinfo['type']=5; //1为积分 2为 金钱 3 为本金  4 为其他  5 为报单币
					$addinfo['userid']=$userinfo['id'];
					$addinfo['dangqian']=$data['money_baodan'];
					$addinfo['source']=5;//4 为管理员操作
					$addinfo['time']=time();
					$addinfo['beizhu']='管理员直接操作，无金额变动数量';
					db('money_log')->insert($addinfo);


			}

            if(empty($data['password'])){
                unset($data['password']);
            }else{
                $data['password'] = md5($data['password']);
            }
            if(empty($data['twopassword'])){
                unset($data['twopassword']);
            }else{
                $data['twopassword'] = md5($data['twopassword']);
            }
            if ($user->update($data)!==false) {
                $result['msg'] = '会员修改成功!';
                $result['url'] = url('index');
                $result['code'] = 1;
            } else {
                $result['msg'] = '会员修改失败!';
                $result['code'] = 0;
            }
            return $result;
        }else{
            $province = db('Region')->where ( array('pid'=>1) )->select ();
            $user_level=db('user_level')->order('sort')->select();
            $info = UsersModel::get($id);
            $this->assign('info',json_encode($info,true));
            $this->assign('title',lang('edit').lang('user'));
            $this->assign('province',json_encode($province,true));
            $this->assign('user_level',json_encode($user_level,true));

            $city = db('Region')->where ( array('pid'=>$info['province']) )->select ();
            $this->assign('city',json_encode($city,true));
            $district = db('Region')->where ( array('pid'=>$info['city']) )->select ();
            $this->assign('district',json_encode($district,true));
            return $this->fetch();
        }
    }

    public function getRegion(){
        $Region=db("region");
        $pid = input("pid");
        $arr = explode(':',$pid);
        $map['pid']=$arr[1];
        $list=$Region->where($map)->select();
        return $list;
    }

    public function usersDel(){
        db('users')->delete(['id'=>input('id')]);
        db('oauth')->delete(['uid'=>input('id')]);
        return $result = ['code'=>1,'msg'=>'删除成功!'];
    }
	//提现驳回
	 public function bohuishenqing(){
		 $id=input('id');

		db('tixian')->update(['id' => $id, 'is_ok' => '2']);
		// 驳回时原路退回提现的金额
		//获取类型以及金额
	    $fan=db('tixian')->where('id='.$id)->find();
		
		//  jifen($type,$userid,$num，$source,$jiajian)
		//  type          1为积分    2为 金钱    3 为本金  4 为其他
		//  $source       1商城消费  2 会员提现  3会员转账  4 管理变动  5 手动充值  6 微信充值
		//  num           数值
		//  $jiajian     1 为 加       2为减
		//  返回结果     1、执行成功   2 余额不足
		
			jifen($fan['type'],$fan['userid'],$fan['num'],7,1,'');
		
			
        return $result = ['code'=>1,'msg'=>'申请已驳回!'];
    }
	//驳回报单申请
		public function bohuibaodan(){
		 $id=input('id');
		 $baodan=db('baodan')->where('id',$id)->find();
		 if($baodan['is_ok']==0){
             db('baodan')->update(['id' => $id, 'is_ok' => '2']);
             return $result = ['code'=>1,'msg'=>'申请已驳回!'];
         }else{
             return $result = ['code'=>-1];
         }
    }
	//完成报单
	 public function baodanok(){
		 $id=input('id');
         $baodan=db('baodan')->where('id',$id)->find();
		 if($baodan['is_ok']==0){
             db('baodan')->update(['id' => $id, 'is_ok' => '1']);
             $baodan=db('baodan')->where('id',$id)->find();
             jihuo($baodan['userid'],$baodan['num']);
             // 此处写报单完成之后的算法
             return $result = ['code'=>1,'msg'=>'打款成功!'];
         }else{
             return $result = ['code'=>-1,'msg'=>'打款成功!'];
         }
    }
		//完成发货
	 public function fahuo(){
		 $id=input('id');
			db('shop_dingdan')->update(['id' => $id, 'is_ok' => '1']);
		// 此处写发货完成之后的算法
        return $result = ['code'=>1,'msg'=>'发货成功!'];
    }
	//取消发货
	public function quxiaofahuo(){
		 $id=input('id');
			db('shop_dingdan')->update(['id' => $id, 'is_ok' => '2']);
		// 此处写取消完成之后的算法
        return $result = ['code'=>1,'msg'=>'取消发货成功!'];
    }
	 public function dakuan(){
		 $id=input('id');
		db('tixian')->update(['id' => $id, 'is_ok' => '1']);
       // db('oauth')->delete(['uid'=>input('id')]);
        return $result = ['code'=>1,'msg'=>'打款成功!'];
    }
    public function delall(){
        $map[] =array('id','IN',input('param.ids/a'));
        db('users')->where($map)->delete();
        $result['msg'] = '删除成功！';
        $result['code'] = 1;
        $result['url'] = url('index');
        return $result;
    }

    /***********************************会员组***********************************/
    public function userGroup(){
        if(request()->isPost()){
            $userLevel=db('user_level');
            $list=$userLevel->order('sort')->select();
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list,'rel'=>1];
        }
        return $this->fetch();
    }
    public function groupAdd(){
        if(request()->isPost()){
            $data = input('post.');
            db('user_level')->insert($data);
            $result['msg'] = '会员组添加成功!';
            $result['url'] = url('userGroup');
            $result['code'] = 1;
            return $result;
        }else{
            $this->assign('title',lang('add')."会员组");
            $this->assign('info','null');
            return $this->fetch('groupForm');
        }
    }
    public function groupEdit(){
        if(request()->isPost()) {
            $data = input('post.');
            db('user_level')->update($data);
            $result['msg'] = '会员组修改成功!';
            $result['url'] = url('userGroup');
            $result['code'] = 1;
            return $result;
        }else{
            $map['level_id'] = input('param.level_id');
            $info = db('user_level')->where($map)->find();
            $this->assign('title',lang('edit')."会员组");
            $this->assign('info',json_encode($info,true));
            return $this->fetch('groupForm');
        }
    }
    public function groupDel(){
        $level_id=input('level_id');
        if (empty($level_id)){
            return ['code'=>0,'msg'=>'会员组ID不存在！'];
        }
        db('user_level')->where(array('level_id'=>$level_id))->delete();
        return ['code'=>1,'msg'=>'删除成功！'];
    }
    public function groupOrder(){
        $userLevel=db('user_level');
        $data = input('post.');
        $userLevel->update($data);
        $result['msg'] = '排序更新成功!';
        $result['url'] = url('userGroup');
        $result['code'] = 1;
        return $result;
    }

    public function server_list(){
            if(request()->isPost()){
                $key=input('post.key');
                $page =input('page')?input('page'):1;
                $pageSize =input('limit')?input('limit'):config('pageSize');
                $list=db('users')
                    ->where('server',1)
                    ->whereOr('server',2)
                    ->order('jihuo_time desc')
                    ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                    ->toArray();
                if(!empty($list)){
                    foreach ($list['data'] as $k=>$v){
                        $list['data'][$k]['jihuo_time'] = date('Y-m-d H:s',$v['jihuo_time']);
                        $list['data'][$k]['is_ok'] =1;
                    }
                }
                return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
            }
            return $this->fetch();
    }


    public function server_ok(){
        $id=input('post.id');
        $is_lock=input('post.is_lock');
        if($is_lock==1){
            $is_ok=2;
        }else{
            $is_ok=0;
        }
            if(db('users')->where('id='.$id)->update(['server'=>$is_ok])!==false){
                return ['status'=>1,'msg'=>'设置成功!'];
            }else{
                return ['status'=>0,'msg'=>'设置失败!'];
            }
    }
    public  function  achievement(){
        if(request()->isPost()){
            $key=input('post.key');
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');

            $list=db('total_achievement')
                ->where('id','gt',0)
                ->order('createtime desc')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['createtime'] = date('Y-m-d H:s',$v['createtime']);
                if($v['new_grant']>0){

                    $b1=sprintf("%.2f", $v['bonus1']/$v['new_grant']*100);
                    $b2=sprintf("%.2f",$v['bonus2']/$v['new_grant']*100);
                    $b3=sprintf("%.2f",$v['bonus3']/$v['new_grant']*100);
                    $b4=sprintf("%.2f",$v['bonus4']/$v['new_grant']*100);
                }else{
                    $b1=0;
                    $b2=0;
                    $b3=0;
                    $b4=0;
                }
                if($v['newadd_achievement']>0){
                    $b5=sprintf("%.2f",$v['new_grant']/$v['newadd_achievement']*100);
                 //   $b5=$v['new_grant']/$v['newadd_achievement']*100;
                }else{
                    $b5=0;
                }
                if($v['all_achievement']>0){
                    $b6=sprintf("%.2f",$v['all_grant']/$v['all_achievement']*100);
                 //   $b6=$v['all_grant']/$v['all_achievement']*100;
                }else{
                    $b6=0;
                }
                $list['data'][$k]['b1']=$b1;
                $list['data'][$k]['b2']=$b2;
                $list['data'][$k]['b3']=$b3;
                $list['data'][$k]['b4']=$b4;
                $list['data'][$k]['b5']=$b5;
                $list['data'][$k]['b6']=$b6;
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }
}